import {Component, OnInit, ViewEncapsulation, OnDestroy, ViewChild, Renderer, ElementRef} from '@angular/core';
import {ActivatedRoute, Params, Router} from "@angular/router";
import {PaymentService} from "@payment/payment.service";
import {ToolsService} from "@shared/service/tools/tools.service";
import {AuthService} from "@shared/service/auth/auth.service";

import {imageUtil} from "@core/globals/globals.service";
import {Observable} from "rxjs";
import {GoodsOrderRespVO, PayInfoRespVO} from "@interface/index";



@Component({
  selector: 'seed-payment-main',
  templateUrl: './payment-main.component.html',
  styleUrls: ['./payment-main.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class PaymentMainComponent implements OnInit, OnDestroy {
  public payType = 0;  //  支付类型0：支付宝，1：微信, 2:微信公众号
  public loading = false;
  public orderInfo: GoodsOrderRespVO;
  public orderNumber = '';
  private userId: string;
  public imageUtil = imageUtil.path;
  private alive: boolean;
  private timer: Observable<number>;
  private interval: number;
  public wechatType: number;  //  微信支付类型1：微信，2：微信公众号
  private wechatParams: PayInfoRespVO;
  @ViewChild('payment') pamentBtn: ElementRef;
  public times = {
    payTimer: null, // 定时器
    nowTime: '',
    day: '0',
    hour: '00',
    minute: '00',
    second: '00',
  };

  constructor(public paymentService: PaymentService,
              public toolsService: ToolsService,
              public route: ActivatedRoute,
              private router: Router,
              private authService: AuthService,
              private renderer: Renderer) {
    this.alive = true;
    this.interval = 1000;
    this.orderInfo = new GoodsOrderRespVO();
    this.userId = this.authService.getUserId();
    this.timer = Observable.timer(0, this.interval);
    this.wechatType = this.toolsService.ua().isWeixin ? 2 : 1;
     //  console.log(`wechatType: ${this.wechatType}`)
  }

  /**
   * @description 获取选择的支付方式,做出不用的动作
   * @author @chenwh576
   * @date 20170926
   * @param $event
   */
  handlePayment($event) {
    this.toolsService.showLoading();
    this.paymentService.getPaymentInfo(this.payType, this.orderNumber)
      .subscribe((res) => {
        this.toolsService.hideLoading();
        if (res.result === '0') {
          const data = res.data;
          this.wechatParams = res.data;
          this.handleAllPay(this.payType, data);
        } else {
          this.toolsService.showToast(res.msg);
        }
      });

  }

  /**
   * @description 选择支付宝支付跳转支付宝中间页面
   * @author @chenwh576
   * @date 20170926
   * @param url
   */
  handleAlipay(url) {
    location.href = url;
  }

  /**
   * @description 选择微信支付跳转至激活iframe src唤醒支付宝
   * @author @chenwh576
   * @date 20170926
   * @param url
   */
  handleWechatPay(url) {
    location.href = this.handleRedirectUrl(url);
    /* this.renderer.setElementAttribute(this.pamentBtn.nativeElement,'src',this.handleRedirectUrl(url));
     setTimeout(() => {
     this.toolsService.presentConfirm('请确认支付是否完成',1,this.goToResultPage.bind(this),null,'重新支付','已完成支付');
     },2000)*/
  }

  handleAllPay(payType: number, data: PayInfoRespVO) {
    switch (payType) {
      case 0:
        this.handleAlipay(data.url);
        break;
      case 1:
        this.handleWechatPay(data.url);
        break;
      case 2:
        this.doWechatPay();
        break;
    }
  }

  showPrompt() {
    this.toolsService.presentConfirm('请确认支付是否完成', 1, this.goToResultPage.bind(this), null, '重新支付', '已完成支付');
  }

  /**
   * @description 改变支付类型
   * @author @chenwh576
   * @date 20170926
   * @param value
   */
  handleChangePayType(value) {
    this.payType = value;
  }

  /**
   * @description 前往支付结果页面
   * @author @chenwh576
   * @date 20170926
   */
  goToResultPage() {
    // this.router.navigate(['/payment/result', this.orderNumber]);
    this.router.navigate(['/payment/result'], {queryParams: {mchOrderNumber: this.orderNumber}});
  }

  /**
   * @description 组装支付宝支付后返回页面url
   * @author @chenwh576
   * @date 20170926
   * @param url
   * @returns {string}
   */
  handleRedirectUrl(url) {
    // const host = location.protocol + '//' + location.host;
    const host = 'https://' + location.host;
    url = url + `&redirect_url=${host}/payment/result?mchOrderNumber=${this.orderNumber}`;
    return encodeURI(url);
  }

  /**
   * @description 获取订单信息
   * @author @chenwh576
   * @date 20170926
   * @param param
   */
  getOrderInfo(param) {
    const params = {
      orderNumber: param
    };
    this.toolsService.showLoading();
    this.paymentService.getOrderInfo(params)
      .subscribe((res) => {
        this.toolsService.hideLoading();
        if (res.result === '0' && res.data) {
          this.orderInfo = res.data;
          this.times.payTimer = setInterval(this.handleCountdown.bind(this), 1000);
        }
      });
  }

  /**
   * @description 调用微信内置jsBridge接口，吊起支付；
   * @author @chenwh576
   * @time 2017-11-23
   */
  onBridgeReady() {
    const {appId, timeStamp, nonceStr, packageWx, signType, paySign} = this.wechatParams;
    WeixinJSBridge.invoke(
      'getBrandWCPayRequest', {
        "appId": appId,      // 公众号名称，由商户传入
        "timeStamp": timeStamp,          // 时间戳，自1970年以来的秒数
        "nonceStr": nonceStr,  // 随机串
        "package": packageWx,
        "signType": signType,
        "paySign": paySign  // 微信签名
      },
      (res) => {
        if (res.err_msg === "get_brand_wcpay_request:ok") {
          this.router.navigate(['/payment/result'], {
            queryParams: {mchOrderNumber: this.orderNumber}});
          return;
        }
        if (res.err_msg === "get_brand_wcpay_request:cancel") {
          alert('您以取消支付.');
          return;
        }
        if (res.err_msg === "get_brand_wcpay_request:fail") {
          alert('支付失败,请刷新后重试');
          return;
        }
      }
    );
  }

  /**
   * @description 微信内发起微信公众号支付
   * @author @chenwh576
   * @date 2017-11-23
   */
  doWechatPay() {
    if (typeof WeixinJSBridge === "undefined") {
      if (document.addEventListener) {
        document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady.bind(this), false);
      } else if (document['attachEvent']) {
        document['attachEvent']('WeixinJSBridgeReady', this.onBridgeReady.bind(this));
        document['attachEvent']('onWeixinJSBridgeReady', this.onBridgeReady.bind(this));
      }
    } else {
      this.onBridgeReady();
    }
  }

  // 处理活动倒计时
  handleCountdown() {
    let t = this.orderInfo.timeExpireSecond -= 1;
    if ( this.orderInfo.status !== 1 || t <= 0 ) { // 订单状态 非 待付款时 则清除定时器，
      t = 0;
      clearInterval(this.times.payTimer);
    }

    let hour, minute, second;
    this.times.day = Math.floor(t / 60 / 60 / 24).toString();
    hour = Math.floor(t / 60 / 60 % 24).toString();
    minute = Math.floor(t / 60 % 60).toString();
    second = Math.floor(t % 60).toString();
    this.times.hour = this.handleTime(hour);
    this.times.minute = this.handleTime(minute);
    this.times.second = this.handleTime(second);
  }
  // 处理个位数时间
  handleTime(time) {
    if (time > 0 && time < 10) {
      return `0${time}`;
    } else {
      return time;
    }
  }

  /**
   * 跳转订单详情页
   * @param orderId
   */
  goToOrderDetail(orderId: number) {
    orderId && this.router.navigate(['/order/detail', orderId]);
  }


  /*  whileOrderInfo(params){
   let param = {
   orderNumber : params
   };
   this.timer
   .takeWhile(() => this.alive)
   .subscribe(() => {
   this.paymentService.getOrderInfo(param)
   .subscribe(res => {
   if(res.data.status == 2){
   this.router.navigate(['/payment/result'],{queryParams:{orderNumber:res.data.orderNumber}});
   }
   })
   })
   }*/

  ngOnInit() {
    this.route.queryParams
      .subscribe((params: Params) => {
        this.orderNumber = params['orderNumber'];
        this.getOrderInfo(this.orderNumber);
        if (params['redirected'] && params['redirected'] === '1') {
          this.showPrompt();
        }
      });
  }

  ngOnDestroy() {
    this.alive = false;
  }

}
